<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="设备名称" prop="eqName">
        <el-input
          v-model="queryParams.eqName"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="设备型号" prop="model">
        <el-input
          v-model="queryParams.model"
          placeholder="请输入设备型号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="操作类型" prop="operationType">
        <el-select
          v-model="queryParams.operationType"
          placeholder="请选择操作类型"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.TESTEQUIPMENTOPR_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['testequipmentuse:test-equipment-use:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['testequipmentuse:test-equipment-use:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
            type="danger"
            plain
            :disabled="isEmpty(checkedIds)"
            @click="handleDeleteBatch"
            v-hasPermi="['testequipmentuse:test-equipment-use:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
        row-key="id"
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
        @selection-change="handleRowCheckboxChange"
    >
    <el-table-column type="selection" width="55" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="设备名称" align="center" prop="eqName" />
      <el-table-column label="设备型号" align="center" prop="model" />
      <el-table-column label="存放位置" align="center" prop="storageLocation" />
      <el-table-column label="操作类型" align="center" prop="operationType">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.TESTEQUIPMENTOPR_TYPE" :value="scope.row.operationType" />
        </template>
      </el-table-column>
      <el-table-column label="操作人" align="center" prop="updater" />
      <el-table-column
        label="操作时间"
        align="center"
        prop="updateTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="160px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="handleView(scope.row)"
            v-hasPermi="['testequipmentuse:test-equipment-use:query']"
          >
            查看
          </el-button>
          
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 - 暂时注释掉，因为当前只需要查看功能 -->
<!-- <TestEquipmentUseForm ref="formRef" @success="getList" /> -->
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { ElMessageBox } from 'element-plus'
import { TestEquipmentUseApi, TestEquipmentUse } from '@/api/testequipmentuse/testequipmentuse'
import { TestEquipmentApi } from '@/api/testequipment/testequipment'
// import TestEquipmentUseForm from './TestEquipmentUseForm.vue'

/** 参试设备使用记录表 列表 */
defineOptions({ name: 'TestEquipmentUse' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<TestEquipmentUse[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  eqName: undefined,
  model: undefined,
  operationType: undefined,
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const response = await TestEquipmentUseApi.getTestEquipmentUsePage(queryParams)
    // 确保正确处理后端返回的数据格式
    list.value = response.list || []
    total.value = response.total || 0
    // 用于调试，检查返回的数据结构和字段
    console.log('接口返回数据:', response)
    if (list.value.length > 0) {
      console.log('第一条记录字段:', Object.keys(list.value[0]))
    }
  } catch (error) {
    console.error('获取列表失败:', error)
    message.error('获取数据失败，请重试')
  } finally {
    loading.value = false
  }
}


/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 查看详情操作 */
const handleView = (row: TestEquipmentUse) => {
  // 创建一个详细信息的对象，包含两个表的所有字段
  const detailInfo = {
    // 参试设备使用记录表字段
    id: row.id,
    eqId: row.eqId,
    operationType: row.operationType,
    remark: row.remark,
    updater: row.updater,
    updateTime: row.updateTime,
    // 关联的设备信息字段
    eqName: row.eqName,
    model: row.model,
    storageLocation: row.storageLocation
  }
  
  // 使用Element Plus的对话框显示详情
  ElMessageBox.alert(
    `
      <div class="detail-info">
        <h4>参试设备使用记录详情</h4>
        <table>
          <tr><td>编号：</td><td>${detailInfo.id || '-'}</td></tr>
          <tr><td>参试设备ID：</td><td>${detailInfo.eqId || '-'}</td></tr>
          <tr><td>设备名称：</td><td>${detailInfo.eqName || '-'}</td></tr>
          <tr><td>设备型号：</td><td>${detailInfo.model || '-'}</td></tr>
          <tr><td>存放位置：</td><td>${detailInfo.storageLocation || '-'}</td></tr>
          <tr><td>操作类型：</td><td>${getIntDictOptions(DICT_TYPE.TESTEQUIPMENTOPR_TYPE).find(dict => dict.value === detailInfo.operationType)?.label || '-'}</td></tr>
          <tr><td>备注：</td><td>${detailInfo.remark || '-'}</td></tr>
          <tr><td>操作人：</td><td>${detailInfo.updater || '-'}</td></tr>
          <tr><td>操作时间：</td><td>${detailInfo.updateTime ? dateFormatter(detailInfo.updateTime) : '-'}</td></tr>
        </table>
      </div>
    `,
    '详情',
    {
      dangerouslyUseHTMLString: true,
      customClass: 'detail-dialog',
      confirmButtonText: '关闭',
      cancelButtonText: '',
      showCancelButton: false
    }
  )
}

/** 添加/修改操作 - 暂时保留但注释掉，避免编译错误 */
// const formRef = ref()
// const openForm = (type: string, id?: number) => {
//   formRef.value.open(type, id)
// }

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await TestEquipmentUseApi.deleteTestEquipmentUse(id)
    message.success(t('common.delSuccess'))
    currentRow.value = {}
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除参试设备使用记录表 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await TestEquipmentUseApi.deleteTestEquipmentUseList(checkedIds.value);
    checkedIds.value = [];
    message.success(t('common.delSuccess'))
    await getList();
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: TestEquipmentUse[]) => {
  checkedIds.value = records.map((item) => item.id!);
}

/** 出库按钮操作 */
const handleOutStorage = async (row: TestEquipmentUse) => {
  try {
    // 确认出库
    await ElMessageBox.confirm('确定要出库吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 更新设备使用状态为已出库
    // 这里需要调用TestEquipmentApi来更新设备状态
    await TestEquipmentApi.updateTestEquipment({
      id: row.eqId, // 使用设备ID而非记录ID
      useStatus: 1 // 已出库状态
    })
    
    // 在使用记录中添加一条记录，并添加存放库房ID
    const storageIdValue = row.storageId && typeof row.storageId === 'number' ? row.storageId : 1;
    console.log('使用的存放库房ID:', storageIdValue, '原始row.storageId:', row.storageId);
    
    // 确保传递正确的参数结构
    const createParams = {
      eqId: row.eqId, // 使用设备ID而非记录ID
      operationType: 1, // 出库操作
      remark: '设备出库操作',
      storageId: storageIdValue // 确保storageId是有效的数字
    };
    console.log('创建使用记录参数:', createParams);
    
    await TestEquipmentUseApi.createTestEquipmentUse(createParams)
    
    message.success('出库成功')
    // 刷新列表
    await getList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('出库操作失败:', error)
      message.error('出库失败: ' + (error instanceof Error ? error.message : String(error)))
    }
  }
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await TestEquipmentUseApi.exportTestEquipmentUse(queryParams)
    download.excel(data, '参试设备使用记录表.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>